<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <script type="text/javascript" src="../js/jquery.js"></script>
    <script type="text/javascript" src="../bootstrap/js/bootstrap.js"></script>
    <script type="text/javascript" src="../js/myUtil.js"></script>

    <link rel="stylesheet" type="text/css" href="../bootstrap/css/bootstrap.css">
    <link rel="stylesheet" type="text/css" href="../bootstrap/css/bootstrap-theme.css">
    <link rel="stylesheet" type="text/css" href="../css/page.css">

</head>
<body>
    <br><br><br>
    <div class="container col-md-8 col-md-offset-2" style="background: #FFF888">

        <br><br><br>
        <div style="font-size: 30px; color: #363636; font-family: 华文中宋,serif; text-align: center">创建贴子</div>
        <br>

        <!--显示当前绑定的贴吧和用户-->
        <div class="col-md-12" style="font-size: 17px">
            <label class="col-md-11  col-md-offset-1" id="postBar" style="color: #0000cc;"></label>
            <label class="col-md-11  col-md-offset-1" id="user" style="color: #0000cc;"></label>
        </div>
        <div class="col-md-12" style="height: 20px"></div>

        <!--贴子的标题、与设置成公告贴选择-->
        <div class="col-md-12">
            <label class="col-md-8 col-md-offset-1" style="font-size: 14px">贴子标题：</label>
            <label class="col-md-2" style="font-size: 14px; text-align: right; cursor: pointer; color: #0000cc; display: none" id="setAsNotice" onclick="setAsNotice()">设置为公告贴</label>
            <input class="col-md-10 col-md-offset-1" type="text" name="postName" style="font-size: 17px; padding: 5px" id="postName"/>
        </div>
        <div class="col-md-12" style="height: 20px"></div>

        <!--内容编辑-->
        <div class="col-md-12">

            <label class="col-md-5  col-md-offset-1" style="font-size: 14px">贴子内容：</label>
            <!--添加图片选择-->
            <label class="col-md-5" style="font-size: 14px; text-align: right; cursor: pointer; color: #0000cc;" onclick="addImage()" unselectable="on" onmousedown="return false;">插入图片</label>
            <input type="file" style="display: none" id="selectImage" onchange="selectOnChange()">
            <!--内容预览-->
            <div class="col-md-10 col-md-offset-1 row-no-gutters" style="height: 300px; font-size: 17px; min-height: 100px; background: white; border: 1px solid black; padding: 5px; overflow: auto" contenteditable="true" id="postContent"><div></div></div>

        </div>
        <div class="col-md-12" style="height: 20px"></div>

        <div class="col-md-12">
            <label class="col-md-11 col-md-offset-1" style="font-size: 14px">验证码：</label>
            <input class="col-md-5 col-md-offset-1" type="text" style="padding: 5px" name="userCode" id="userCode"/>
            <!--显示验证码-->
            <div class="col-md-5 col-md-offset-1" id="code"></div>
        </div>
        <div class="col-md-12" style="height: 20px"></div>

        <div class="col-md-12">
            <label class="col-md-6 col-md-offset-3" style="font-size: 14px; color: #FF0000" id="tip"></label>
        </div>

        <div class="col-md-12" style="height: 20px"></div>
        <div class="row" style="font-size: 17px">
            <button class="col-md-2 col-md-offset-3" id="register" onclick="cancel()">取消</button>
            <button class="col-md-2 col-md-offset-2" id="login" onclick="create()">创建</button>
        </div>

        <br><br><br>
    </div>

    <script type="text/javascript">
        let user, postBar;
        let postName = $("#postName");
        let postContent = $("#postContent");
        let postCode = $("#postCode");
        let tip = $("#tip");
        let selectImage = $("#selectImage");

        // 存放验证码
        let seCode;
        userCode = $("#userCode");

        // 引入验证码
        $("#code").load("securityCode.html", function (){
            seCode = nowCode;
            myCallback = getCode;
        });

        // 获取验证码的回调函数
        function getCode(code) {
            seCode = code;
        }

        // 请求得到用户信息
        $.ajaxSettings.async = false;
        $.post("/QG_PostBar/user?method=getUserBySession", function (data){
            user = data;
            $("#user").html("当前用户：" + user.userName);
        }, "json");

        // 请求得到贴吧信息
        $.post("/QG_PostBar/postBar?method=getPostBarBySession", function (data){
            postBar = data;
            $("#postBar").html("所属贴吧：" + postBar.postBarName);

            // 判断当前用户是否为贴吧创建者，是则出现设置为公告帖选项
            if (user.userId === postBar.userId) {
                $("#setAsNotice").show();
            }
        }, "json");
        $.ajaxSettings.async = true;

        // 使用别的按钮调用文件上传界面
        function addImage() {
            selectImage.click();
        }

        // 图片上传后进入预览状态
        function selectOnChange() {
            //判断文件类型,是否为指定格式的图片
            const suffix = selectImage.val().substring(selectImage.val().lastIndexOf(".") + 1).toLowerCase();
            if(!(suffix === "png" || suffix ==="jpg" || suffix === "jpeg")){
                alert("必须上传 png、jpg 或 jpeg 格式的图片!");
                return false;
            }

            //判断文件大小
            const size = selectImage[0].files[0].size;
            if (size > 5 * 1024 * 1024) {
                alert("图片大小不能大于 5M! ");
                return false;
            }

            // 一切就绪，上传图片！！！
            const formData = new FormData();
            formData.append("file", selectImage[0].files[0]);
            $.ajax({
                type : "post",
                url : "/QG_PostBar/post?method=setPostImage",
                data : formData,
                processData : false,
                contentType : false,
                success : function(data){
                    if (data === "error") {
                        alert("图片上传失败!");
                    } else {
                        // 先判断编辑框有没有得到焦点
                        if (document.activeElement.id === "postContent") {
                            // 有的话将图片插入到div的光标位置处
                            var range, node;
                            if (window.getSelection && window.getSelection().getRangeAt) {
                                range = window.getSelection().getRangeAt(0);
                                range.collapse(false);
                                node = range.createContextualFragment("<img style='max-width: 100%; window.event.returnValue=false; max-height: 100%' src='/QG_PostBar/post_Image/" + data + "'/>");
                                var c = node.lastChild;
                                range.insertNode(node);
                                if (c) {
                                    range.setEndAfter(c);
                                    range.setStartAfter(c)
                                }
                                var j = window.getSelection();
                                j.removeAllRanges();
                                j.addRange(range);
                            }
                        } else {
                            // 没有的话将图片添加到编辑框的最后
                            postContent.append("<img style='max-width: 100%; window.event.returnValue=false; max-height: 100%' src='/QG_PostBar/post_Image/" + data + "'/>")
                        }
                    }
                }
            });
        }

        // 监听输入框的变化，有图片被删除就需要在服务器中删除对应已经上传的图片
        var observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                // 如果检查到删除操作，且删除的为图片时
                $(mutation.removedNodes).each(function(value, index) {
                    if(this.nodeType === 1 && this.src !== undefined) {
                        console.log(this);
                        // 截取出图片的名称
                        let imageName = this.src.substring(this.src.lastIndexOf("/")+1);
                        // 然后交给服务器删除该上传的图片
                        $.get("/QG_PostBar/post?method=deletePostImage", {"imageName": imageName}, function (data){
                            if (data !== "true") {
                                alert("删除图片失败！");
                            }
                        })
                    }
                });
            });
        });

        // 还不能这么干，先注释掉
        // var config = { attributes: true, childList: true, characterData: true , subtree: true};
        // observer.observe($('#postContent')[0], config);

        // 设置为公告帖
        function setAsNotice() {
            if (postBar.postAdminId === undefined) {
                postBar.postAdminId = user.userId;
                $("#setAsNotice").css("color", "#FF0000");
            } else {
                postBar.postAdminId = undefined;
                $("#setAsNotice").css("color", "#0000cc");
            }
        }



        function cancel() {
            window.location.href = "postBarContent.html";
        }

        // 创建贴子时，保存整一个 div 的内容到数据库中
        function create() {
            if (check()) {
                // 保存到数据库
                $.post("/QG_PostBar/post?method=createPost", {"postBarId": postBar.postBarId, "userId": user.userId , "postName": postName.val(), "postContent": postContent.html(), "postAdminId": postBar.postAdminId}, function (data) {
                    if (data.postName != null) {
                        tip.html("创建成功！");
                        window.location.href = "postContent.html";
                    } else {
                        tip.html("创建失败！请再次尝试");
                    }
                }, "json");
            }
        }

        function check() {
            if (postName.val().length < 3) {
                tip.html("贴子标题长度必须大于等于 3 ！");
                return false;
            } else if (postContent.html() === "") {
                tip.html("贴子内容不能为空 ！");
                return false;
            } else if (postCode.val() === "") {
                tip.html("验证码不能为空！");
                return false;
            } else if (userCode.val() !== seCode) {
                tip.html("验证码错误，请重新输入！");
                return false;
            } else return true;
        }
    </script>
</body>
</html>